import xl from '@/assets/images/tj.png';
import yc from '@/assets/images/yc.png';
import hc from '@/assets/images/hc.png';
import hs from '@/assets/images/hs.png';
import jd from '@/assets/images/jd.png';
import wsj from '@/assets/images/wsj.png';
import tcc from '@/assets/images/tcc.png';

import xlActive from '@/assets/images/xl_active.png';
import ycActive from '@/assets/images/yc_active.png';
import hcActive from '@/assets/images/hc_active.png';
import hsActive from '@/assets/images/hs_active.png';
import jdActive from '@/assets/images/jd_active.png';
import wsjActive from '@/assets/images/wsj_active.png';
import tccActive from '@/assets/images/tcc_active.png';
import locationIcon from '@/assets/images/location_icon.png';
import { useRoute } from 'vue-router';

export default ({ mapId }) => {
    let map = null;
    // 1景点,2中餐,3茶饮,4小吃,5酒店,6公共厕所,7停车场,8游客中心,9医务室,10演出,11管理局
    const typeMap = {
        xl: xl,
        10: yc,
        3: hc,
        4: hs,
        1: jd,
        6: wsj,
        7: tcc,
    }

    const typeMapActive = {
        xl: xlActive,
        10: ycActive,
        3: hcActive,
        4: hsActive,
        1: jdActive,
        6: wsjActive,
        7: tccActive,
    }

    const resolutions = [262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1];

    const createMaker = (data, type, handler) => {
        const createDOM = (data) => {
            const label = document.createElement('div');
            label.classList.add('label');

            const title = document.createElement('div');
            title.classList.add('title');
            const titleText = data.title || data.businessName;
            title.style.width = titleText.length + 'em';
            title.innerHTML = titleText;

            const icon = document.createElement('img');
            icon.classList.add('icon');
            icon.src = typeMap[type];

            label.appendChild(title);
            label.appendChild(icon);

            label.addEventListener('click', (e) => {
                console.log(e);
                handler && handler(data);
            })

            return label;
        }
        const customOverlay = new BMapGL.CustomOverlay(createDOM, {
            point: new BMapGL.Point(...data.point),
            opacity: 1,
            enableMassClear: true,
            enableDraggingMap: false,
            zIndex: 9,
            properties: { ...data },
        });
        customOverlay.addEventListener('click', () => {
            console.log('click', e);
            handler && handler(data);
        })
        return customOverlay;
        // 创建图标
        // const myIcon = new BMapGL.Icon(typeMap[type], new BMapGL.Size(36, 36), {
        //     imageSize: new BMapGL.Size(36, 36)
        // });
        // // 创建Marker标注，使用小车图标
        // let pt = new BMapGL.Point(...data.point);

        // let marker = new BMapGL.Label(label, {
        //     position: pt,
        // });
        // marker.setStyle({
        //     backgroundColor: 'transparent',
        //     border: 'none'
        // });
        // marker.addEventListener('click', () => {
        //     handler && handler(data);
        // })
        // return marker;
    }

    const addMaker = (makers = [], type = 1, handler) => {
        map.clearOverlays();
        const _makers = makers.map(item => createMaker(item, type, handler));
        _makers.map(item => {
            map.addOverlay(item);
        })
    }
    const addPolyline = (polyline = [], type = 1) => {
        map.clearOverlays();
        const line = polyline.map(item => {
            return new BMapGL.Point(...item.point);
        })
        var _polyline = new BMapGL.Polyline(line, {
            strokeColor: "blue",
            strokeWeight: 2,
            strokeOpacity: 0.5,
            strokeStyle: 'dashed',
            strokeTexture: {
                url: './imgs/Icon_road_blue_arrow.png',
                width: 16,
                height: 64
            },
            strokeWeight: 8,
            strokeOpacity: 0.8,
        });
        map.addOverlay(_polyline);
    }

    let timer;
    let i = 0.0005;

    const stop = () => {
        clearInterval(timer);
        console.log(map.getBounds(), i);
    }

    const route = useRoute();
    const isAdmin = route.query.isAdmin;
    const getBounds =  () => {
        const i = 0.0025
        // 左下
        var pStart = new BMapGL.Point(103.97321084838742 - i, 30.314224190361887 + i);
        // 右上
        var pEnd = new BMapGL.Point(103.99130391999653 - i, 30.337028744197937 + i + (i / 10) + (i / 10) + (i / 10));
        var bounds = new BMapGL.Bounds(new BMapGL.Point(pStart.lng, pEnd.lat), new BMapGL.Point(pEnd.lng, pStart.lat));
        return bounds;
    }

    const init = () => {
        map = new BMapGL.Map(mapId);
        map.setMinZoom(4);
        map.setMaxZoom(21);
        console.log(map);
        // map.setHeading(-120);
        map.setDisplayOptions({
            poiText: false,  // 隐藏poi标注
            poiIcon: false,  // 隐藏poi图标
            building: false  // 隐藏楼块
        });

        const bounds = getBounds();
        var imgOverlay = new BMapGL.GroundOverlay(bounds, {
            type: 'image',
            url: './hlxmap.png',
            opacity: 1,
            enableMassClear: false,
            zIndex: 8
        });
        map.setBounds(bounds);
        map.addOverlay(imgOverlay);

        // timer = setInterval(() => {
        //     i += 0.0005;
        //     move(i);
        // }, 1000)

        map.centerAndZoom(new BMapGL.Point(103.97704419299893, 30.322043823539282), 17);

        // const setHeading90 = new BMapGL.ViewAnimation([{
        //     heading: 0
        // }])
        // map.startViewAnimation(setHeading90);
        // 创建位置点
        // var custom = new BMapGL.XYZLayer({
        //     useThumbData: true,
        //     // 自定义图层瓦片请求地址，可使用xTemplate，yTemplate，zTemplate匹配自定义网格编号规则
        //     tileUrlTemplate: './tiles/[z]/tile-[x]_[y].png',
        // });
        // map.addTileLayer(custom);

        // const tileLayer = new BMapGL.TileLayer({ isTransparentPng: false });
        // tileLayer.getTilesUrl = function (tileCoord, zoom) {
        //     const x = tileCoord.x;
        //     const y = tileCoord.y;
        //     return './tiles/' + zoom + '/tile-' + x + '_' + y + '.png';
        // }
        // const MyMap = new BMapGL.MapType('MyMap', tileLayer, { minZoom: 4, maxZoom: 8 });
        // {mapType: MyMap}
        // map.addTileLayer(tileLayer);
        // const bpc = new BaiduPointConvert();
        if (isAdmin) {
            map.addEventListener('click', function (e) {
                console.log('点击的经纬度：', e);
                alert(`${e.latlng.lng}, ${e.latlng.lat}`);
            });
        }
        // map.addEventListener('click', function (e) {
        //     console.log('点击的经纬度：', e,
        //     );
        // });

        //设置可视视野范围

        // var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
        // if (isMobile) {//手机端
        //     map.addEventListener("dragend", function (type, target) {
        //         console.log(bounds.containsBounds(map.getBounds()));
        //         if (bounds.containsBounds(map.getBounds())) {
        //         } else {
        //             map.panTo(bounds.getCenter(), map.getZoom());
        //         }
        //     });
        // } else {//PC端
        //     try {
        //         BMapGLLib.AreaRestriction.setBounds(map, b); // 以map为中心，已b为范围的地图
        //     } catch (e) {
        //         console.log(e);
        //         // alert(e);
        //     }
        // }
    }

    const getLocation = async () => {
        return new Promise((resolve, reject) => {
            var geolocation = new BMapGL.Geolocation();
            // 开启SDK辅助定位
            geolocation.enableSDKLocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    resolve(r);
                } else {
                    reject(r);
                }
            });
        })

    }


    let centerOverlay = null;
    const setLocationCenter = async () => {
        try {
            map.removeOverlay(centerOverlay);
            try {
                const currentLocation = await getLocation();
                const point = new BMapGL.Point(currentLocation?.point.lng, currentLocation?.point.lat);
                const bounds = getBounds();
                if (bounds.containsPoint(point)) {
                    const locationIcon2 = new BMapGL.Icon(locationIcon, new BMapGL.Size(24, 30), {
                        imageSize: new BMapGL.Size(24, 30)
                    });
                    centerOverlay = new BMapGL.Marker(point, {
                        icon: locationIcon2
                    })
                    map.addOverlay(centerOverlay);
                    map.panTo(point);
                } else {
                    alert('您不在景区内');
                }
            } catch (error) {
                alert('请开启定位权限')
            }
            
        } catch (error) {
            console.log(error);
        }
    };

    return { stop, map, init, addMaker, addPolyline, getLocation, setLocationCenter }
}
